package com.urbane.generator.controller;

import com.urbane.generator.entity.GenConfig;
import com.urbane.generator.service.CodeGeneratorService;
import jakarta.annotation.Resource;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("/generator")
public class CodeGeneratorController {

    @Resource
    private CodeGeneratorService codeGeneratorService;

    @PostMapping("/generate")
    public ResponseEntity<FileSystemResource> generateCode(@RequestBody GenConfig config) throws IOException {

        // 生成代码到临时目录
        codeGeneratorService.generate(config);

        // 将生成的代码打包为 ZIP
        File zipFile = codeGeneratorService.packageToZip(config.getOutputDir());

        // 返回 ZIP 文件流
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=generated-code.zip")
                .contentType(MediaType.APPLICATION_OCTET_STREAM)
                .body(new FileSystemResource(zipFile));
    }
}